<?php
/**
 * Created by PhpStorm.
 * User: chenx
 * Date: 18-3-6
 * Time: 下午5:02
 */

namespace common\models;


use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use common\models\GoogsAttr;
use common\models\Shop;
class Goods extends ActiveRecord
{
    public static function tableName()
    {
        return 'goods';
    }

    public function rules()
    {
        return [
            [['goods_name','list_img','introduction'],'string'],
            [['shop_id','three_tree_id','two_tree_id','one_tree_id','created_at','updated_at',
                'is_del','sales_volume','display_sales','status'],'integer'],
            [['freight'],'double']
        ];

    }

    public function attributeLabels()
    {
        return [
            'id	'=> 'id',
            'goods_name'=> '商品名称',
            'tree_id'=> '分类id',
            'shop_id'=> '商家id',
            'list_img'=>'列表图',
            'introduction	'=> '简介',
            'freight	'=> '创建时间',
            'created_at	'=> '创建时间',
            'updated_at'=>'修改时间',
            'is_del'=>'修改时间',
            'sales_volume'=>'销量',
            'display_sales'=>'以团销量',
            'status'=>'上下架',
        ];
    }


    /**
     * @param $data
     * @param int $type 1：总后台
     * @return mixed
     */
    public  function GetgoogsList($data,$type=0){

        $goodsId = array_column($data,'id');

        $pre = GoodsAttr::find()->select(['goods_id,max(original_price) as max_pre', 'min(original_price) as min_pre'])
            ->andwhere(['in','goods_id',$goodsId])
            ->groupBy('goods_id')
            ->orderBy(['goods_id'=>SORT_DESC])
            ->asArray()
            ->all();
        $newpre = [];

        foreach ($pre as $jg){
            $newpre[$jg['goods_id']] = $jg;
        }
        if($type == 1){
            $shopArr = array_column($data,'shop_id');
            $shop = Shop::find()->select('id,shop_name')
                ->where(['in','id',$shopArr])->asArray()->all();
        }
        foreach ($data as &$val){
            if($type == 1){
                foreach ($shop as $sid){
                    if($val['shop_id'] == $sid['id']){
                        $val['shop_name'] = $sid['shop_name'];
                    }
                }
            } else {
                $val['shop_name'] = '';
            }

            if(isset($newpre[$val['id']])){
                $val['org_pre'] = $newpre[$val['id']]['min_pre'] . '~' . $newpre[$val['id']]['max_pre'];
            } else {
                $val['org_pre'] = '0~0';
            }
        }
        return $data;
    }

}